package info.thereisonlywe.core.essentials;

import java.util.Random;

/**
 * 
 * @author thereisonlywe
 */
public class MathEssentials {

	public static int getClosestToRadix(int[] values, int radix)
	{
		int previndex = 0;
		int bestValue = Integer.MAX_VALUE;
		for (int i = 0; i < values.length; i++)
		{
			int tmp = Math.abs(radix - values[i]);
			if (tmp < bestValue)
			{
				previndex = i;
				bestValue = tmp;
			}
		}
		return previndex;
	}

	public static int getMin(int[] values)
	{
		return getClosestToRadix(values, Integer.MIN_VALUE);
	}

	public static int getMinValue(int[] values)
	{
		return values[getMin(values)];
	}

	public static int getMax(int[] values)
	{
		return getClosestToRadix(values, Integer.MAX_VALUE);
	}

	public static int getMaxValue(int[] values)
	{
		return values[getMax(values)];
	}

	public static int newRandom(int lastValueAllowed)
	{
		Random r = new Random();
		int randint = r.nextInt(lastValueAllowed + 1);
		return randint;
	}

	public static int newRandom()
	{
		Random r = new Random();
		int randint = r.nextInt(Integer.MAX_VALUE);
		return randint;
	}

	/**
	 * @param lat1
	 * @param lon1
	 * @param lat2
	 * @param lon2
	 * @return distance in kilometers.
	 */
	public static double getDistance(double lat1, double lon1, double lat2,
			double lon2)
	{
		double theta = lon1 - lon2;
		double dist = Math.sin(convertDegreesToRadians(lat1))
				* Math.sin(convertDegreesToRadians(lat2))
				+ Math.cos(convertDegreesToRadians(lat1))
				* Math.cos(convertDegreesToRadians(lat2))
				* Math.cos(convertDegreesToRadians(theta));
		dist = Math.acos(dist);
		dist = convertRadiansToDegrees(dist);
		dist = dist * 60 * 1.1515;
		dist = dist * 1.609344;
		return dist; // km
	}

	public static double convertDegreesToRadians(double deg)
	{
		return (deg * Math.PI / 180.0);
	}

	public static double convertRadiansToDegrees(double rad)
	{
		return (rad * 180.0 / Math.PI);
	}

}
